import requests
from concurrent.futures import ThreadPoolExecutor, as_completed
import time

# 查询的名称列表
names = [
'《药品经营许可证》（批发）核发',
'《药品经营许可证》（零售连锁总部）核发',
'《药品经营许可证》（批发）换发',
'《药品经营许可证》（零售连锁总部）换发',
'《药品经营许可证》（批发）许可事项变更',
'《药品经营许可证》（零售连锁总部）许可事项变更',
'《放射性药品使用许可证》变更许可',
'科研和教学用毒性药品购买审批（省级）',
'企业从事麻醉药品、第一类精神药品区域性批发审批',
'第一类中的药品类易制毒化学品经营许可 ',
'区域性批发企业跨省级行政区域向医疗机构销售麻醉药品、第一类精神药品许可  ',
'全国性批发企业向医疗机构销售麻醉药品、第一类精神药品许可',
'《放射性药品使用许可证》核发许可 ',
'企业专门从事第二类精神药品批发审批',
'《放射性药品经营许可证》核发审批',
'《放射性药品经营许可证》变更审批',
'《放射性药品经营许可证》延续审批',
'医疗用毒性药品批发企业许可',
'化妆品生产变更许可',
'化妆品生产首次许可',
'国产第二类医疗器械首次注册',
'国产第二类医疗器械变更注册',
'国产第二类医疗器械延续注册',
'第二、三类医疗器械生产延续许可',
'第二、三类医疗器械生产首次许可',
'第二、三类医疗器械生产许可事项变更许可',
'购买科研和教学用麻醉药品、精神药品审批',
'购买麻醉药品和精神药品标准品、对照品审批',
'第二类精神药品原料药需用计划备案',
'医疗机构中药制剂委托配制备案（已取得《医疗机构制剂许可证》）',
'医疗机构中药制剂委托配制备案 （已取得《医疗机构制剂许可证》）延续申请',
'《放射性药品生产许可证》核发审批',
'第一类中的药品类易制毒化学品生产许可',
'麻醉药品、精神药品生产企业许可',
'医疗机构配制制剂品种再注册',
'国家药监局规定的特殊制剂以外的制剂在本省行政区域内调剂使用审批',
'医疗机构应用传统工艺配制中药制剂备案',
'首次申请医疗机构中药制剂委托配制备案 （未取得《医疗机构制剂许可证》）',
'医疗机构中药制剂委托配制备案（未取得《医疗机构制剂许可证》）延续',
'医疗机构配制制剂品种补充申请',
'医疗机构配制制剂品种注册',
'第一类中的药品类易制毒化学品购买许可',
'中药保护初次保护审批',
'中药保护同品种保护审批',
'中药保护变更审批',
'中药保护延长保护期审批',
'《医疗机构制剂许可证》核发',
'药品生产许可证核发',
'《放射性药品生产许可证》延续审批',
'《医疗机构制剂许可证》换发',
'药品生产许可重新发证',
'药品生产许可许可事项变更',
'《放射性药品生产许可证》变更审批',
'《医疗机构制剂许可证》变更',
'非药品生产企业购买咖啡因审批',
'境内生产药品再注册',
]

# 请求的目标URL
url = "http://59.215.206.188/sxgl/mng/project/change/info/query"

# 请求头
headers = {
    'Accept': 'application/json, text/javascript, */*; q=0.01',
    'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
    'Connection': 'keep-alive',
    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
    'Origin': 'http://59.215.206.188',
    'Referer': 'http://59.215.206.188/sxgl/mng/project/change/info/index?v=1763965365559',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36',
    'X-Requested-With': 'XMLHttpRequest',
    'Cookie': 'JSESSIONID=EABEB746D1C72BE53582BCE84C3C4FA3; wyhijack=/ddgl/static/normalize/gov-work.js_1762737662093; tempTokenKey=eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiLnhormr4UiLCJhdWQiOiI5RTEwNTlDOTMzNUQ0QzdDQjhEQzc0MDBEMDNBRUNGQiIsInNlcnZlciI6Imh0dHA6Ly81OS4yMTUuMjA2LjE4OC9sb2dpbi8iLCJyb2xlIjoiUk9MRV9BUkVBLFJPTEVfV0lORE9XIiwiaXNJbml0aWFsUGFzc3dvcmQiOiIwIiwicmVnaW9uTmFtZSI6Iui0teW3nuecgSIsImluZHVzdHJ5IjpudWxsLCJhcHBDb2RlIjoiZGdvdi1wb3J0YWwiLCJvcmdhbk5hbWUiOiLotLXlt57lpKfmlbDmja7pm4blm6IiLCJyZWdpb25Db2RlIjoiNTIwMDAwIiwiaW5kdXN0cnlMaXN0IjpudWxsLCJvcmdhbkNvZGUiOiI1MjAwMDAyMDE3MDIxNjEwMDUzMDAwMDUwNyIsImV4cGlyYXRpb25UaW1lIjo3MSwiZ3JhZGUiOiIyIiwic3RhdHVzIjoiMSIsImlzcyI6Imluc3B1ciIsImlhdCI6MTc2Mzk0NjE2MiwiZXhwIjoxNzYzOTc0OTYyfQ.e3VhmoxZ9pOnrlKD84TeKMADdD2XR5e4ChccA6lkUVQQAuU4EeanemzkjSCF1JgNvExaN3wEza3TQBSlT0NudA; userInfoKey={%22role%22:%22ROLE_AREA%2CROLE_WINDOW%22%2C%22isInitialPassword%22:%220%22%2C%22regionName%22:%22%E8%B4%B5%E5%B7%9E%E7%9C%81%22%2C%22appCode%22:%22dgov-portal%22%2C%22organName%22:%22%E8%B4%B5%E5%B7%9E%E5%A4%A7%E6%95%B0%E6%8D%AE%E9%9B%86%E5%9B%A2%22%2C%22regionCode%22:%22520000%22%2C%22phone%22:%22384d53fa06a4844cfd54260b048c33e9%22%2C%22organCode%22:%2252000020170216100530000507%22%2C%22expirationTime%22:71%2C%22name%22:%221342b48e6f8f39ea7ba36accc05b61a8%22%2C%22id%22:%229E1059C9335D4C7CB8DC7400D03AECFB%22%2C%22email%22:%223f9980534589201ab2c5f2481db36392%22%2C%22username%22:%2247d57692a252657367001b6a2ff35333%22%2C%22status%22:%221%22%2C%22isWeakPwd%22:%220%22}; pwdState=true; inspurRoleKey=ROLE_AREA; windowId=0B7CA12E92004E0ABCA9EB88F0A792E4; James_cookie_sYQDUGqqzHtheme=custom; wyhtml=/ddglzy/_19ab370d9dcf892_1763947108828; webfinal.session.errorCount=0',
}

def query_single_item(name):
    """
    单个查询任务的函数
    :param name: 要查询的项目名称
    :return: 一个包含查询名称和结果的字典
    """
    payload = {
        "_search": "true",
        "nd": str(int(time.time() * 1000)),
        "rows": "10",
        "page": "1",
        "sidx": "",
        "sord": "",
        "name": name,
        "code": "",
        "org_code": "",
        "regionCode": "520000",
        "type": "",
        "policy_type": "",
        "is_online": "",
        "status": ""
    }

    try:
        # 发送POST请求，verify=False 忽略SSL证书验证
        response = requests.post(url, headers=headers, data=payload, timeout=10, verify=False)
        response.raise_for_status()

        result_data = response.json()

        # 提取 CODE
        code = None
        if result_data and 'rows' in result_data and len(result_data['rows']) > 0:
            code = result_data['rows'][0]['cell'].get('CODE')

        return {
            'name': name,
            'success': True,
            'code': code
        }

    except Exception as e:
        return {
            'name': name,
            'success': False,
            'error': str(e)
        }


def main():
    """
    主函数，使用线程池执行多线程查询
    """
    print("--- 开始查询所有项目的 CODE ---")
    start_time = time.time()

    max_workers = 10
    all_results = []

    with ThreadPoolExecutor(max_workers=max_workers) as executor:
        future_to_name = {executor.submit(query_single_item, name): name for name in names}

        for future in as_completed(future_to_name):
            result = future.result()
            all_results.append(result)
        print(all_results)

    end_time = time.time()

    print(f"\n--- 查询完成，总耗时: {end_time - start_time:.2f} 秒 ---\n")

    # # 打印所有结果
    # for res in all_results:
    #     if res['success']:
    #         # print(f"名称: {res['name']}")
    #         # print(f"CODE: {res['code']}\n")
    #         print(str(res['code']))
    #     else:
    #         print(f"名称: {res['name']}")
    #         print(f"查询失败: {res['error']}\n")


if __name__ == "__main__":
    main()